<script lang="ts" setup>
import type { CatalogListData } from './index';

import { computed, onBeforeMount, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { useAppConfig } from '@vben/hooks';
import { ElSearch } from '@vben/icons';

import { StorageManager } from '@vben-core/shared/cache';

import { ElButton, ElCard, ElInput, ElPagination, ElTag } from 'element-plus';

import { publicResourcesApi, userApi } from '#/api';
import { $t } from '#/locales';
import { router } from '#/router';
import { getMtdeUrl } from '#/utils';

import { HistoricalMap } from './components';

const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});
const isLoading = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const keyword = ref('');
const selectedTag = ref('矢量服务');
const showHistorical = ref(false);
const { adminEmail } = useAppConfig(import.meta.env, import.meta.env.PROD);
const isAdmini = ref(false);
const catalogList = reactive({
  data: [] as CatalogListData[],
});
const adminInfo = ref(
  {} as {
    avatar: string;
    email: string;
    institution: string;
    userName: string;
  },
);

const isAdmin = () => {
  if (storageManager.getItem('email') === adminEmail) isAdmini.value = true;
};
const refreshPublicResources = async () => {
  // 判断请求的类型
  const isVectorService = selectedTag.value === '矢量服务';
  const fetchFunction = isVectorService
    ? publicResourcesApi.getVecList
    : publicResourcesApi.getRasList;

  // 发起请求
  const response = await fetchFunction(
    pageSize.value,
    currentPage.value,
    keyword.value,
  );

  // 更新数据
  catalogList.data = response.body;
  total.value = response.count;
  // 设置加载状态为完成
  isLoading.value = false;
};
function selectTag(tag: string) {
  selectedTag.value = tag;
  refreshPublicResources();
}
const selectedFileType = ref<null | string>(null);

const filteredFiles = computed(() => {
  if (selectedFileType.value) {
    return catalogList.data.filter(
      (file) => file.type === selectedFileType.value,
    );
  }
  return catalogList.data;
});

const getAdminInfo = async () => {
  const res = await userApi.getUserInfoByEmail(adminEmail);
  adminInfo.value = res;
};

const handleSizeChange = (_val: number) => {};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  refreshPublicResources();
};

// 跳转历史疆域地图浏览页面
const navigateToHistoricalMap = () => {
  router.push({
    name: 'historicalmapBrowse',
    // path: '/historicalmap-browse'
  });
};

onBeforeMount(async () => {
  isLoading.value = true;
  isAdmin();
  refreshPublicResources();

  await getAdminInfo();
});
</script>

<template>
  <Page
    oncontextmenu="return false"
    onselectstart="return false"
    title=""
    auto-content-height
    class="flex h-full flex-col"
  >
    <template #title>
      <div class="flex">
        <div
          class="mt-2 flex w-1/4 min-w-[220px] flex-shrink-0 flex-nowrap gap-6 whitespace-nowrap"
        >
          <span
            v-for="tag in ['矢量服务', '栅格服务']"
            :key="tag"
            @click="selectTag(tag)"
            class="cursor-pointer rounded-full px-4 py-1 text-sm transition-all"
            :class="
              selectedTag === tag
                ? 'bg-black text-white'
                : 'bg-gray-100 text-gray-700'
            "
          >
            {{ tag }}
          </span>
        </div>
        <ElInput
          v-model="keyword"
          size="large"
          :placeholder="$t('page.resources.searchPlaceholder')"
          clearable
        >
          <template #append>
            <ElButton :icon="ElSearch" @click="refreshPublicResources" />
          </template>
        </ElInput>
      </div>
    </template>

    <!-- 主要内容区域 -->
    <div class="relative flex h-full w-full flex-1">
      <!-- 默认内容 -->
      <div
        v-if="!showHistorical"
        class="w-full overflow-y-auto bg-white p-4 dark:bg-black"
      >
        <!-- 实际文件内容 -->
        <div
          v-if="!isLoading"
          class="grid gap-4 md:grid-cols-1 lg:grid-cols-1 xl:grid-cols-2"
        >
          <template v-if="selectedTag === '矢量服务'">
            <ElCard
              shadow="hover"
              class="mx-auto w-full max-w-md overflow-hidden rounded-2xl p-0 shadow-lg transition-all hover:scale-[1.01] dark:bg-gray-900"
              :body-style="{ padding: '0' }"
              @dblclick="navigateToHistoricalMap"
            >
              <!-- 历史背景图片 -->
              <div class="h-48 w-full overflow-hidden">
                <img
                  :src="getMtdeUrl('history_bg')"
                  alt="历史疆域地图"
                  class="h-full w-full object-cover"
                />
              </div>

              <!-- 卡片内容 -->
              <div class="p-6">
                <h3
                  class="mb-2 text-lg font-semibold text-gray-800 dark:text-gray-100"
                >
                  跨越时空的疆域地图
                </h3>

                <p
                  class="mb-4 text-sm leading-relaxed text-gray-600 dark:text-gray-400"
                >
                  该服务融合从 <strong>BC3200</strong> 至
                  <strong>AD1900</strong>
                  的主要王朝疆域边界，借助时间维度探索中国历史的时空变迁，适用于科研与可视化演示。
                </p>

                <div class="mb-4 flex flex-wrap gap-2 text-xs">
                  <ElTag type="info">历史地图</ElTag>
                  <ElTag type="warning">公元前3200 - 公元1900</ElTag>
                  <ElTag type="success">疆域变迁</ElTag>
                </div>

                <div class="text-right text-xs italic text-gray-400">
                  双击卡片查看详情
                </div>
              </div>
            </ElCard>
            <ElCard
              shadow="hover"
              class="mx-auto w-full max-w-md overflow-hidden rounded-2xl p-0 shadow-lg transition-all hover:scale-[1.01] dark:bg-gray-900"
              :body-style="{ padding: '0' }"
              @dblclick="$router.push('/quick-start/data')"
            >
              <!-- 背景图，可替换为 earth.jpg 或其他 -->
              <div class="h-48 w-full overflow-hidden">
                <img
                  :src="getMtdeUrl('earth')"
                  alt="公共 GIS 矢量服务"
                  class="h-full w-full object-cover"
                />
              </div>

              <!-- 卡片内容 -->
              <div class="p-6">
                <h3
                  class="mb-2 text-lg font-semibold text-gray-800 dark:text-gray-100"
                >
                  公共 GIS 矢量服务
                </h3>

                <p
                  class="mb-4 text-sm leading-relaxed text-gray-600 dark:text-gray-400"
                >
                  该服务提供共享的公共 GIS
                  矢量服务资源，可方便快捷的导入至个人服务，用于在可视化场景中进行地图配置。
                </p>

                <div class="mb-4 flex flex-wrap gap-2 text-xs">
                  <ElTag type="primary">矢量服务</ElTag>
                  <ElTag type="info">地图可视化</ElTag>
                  <ElTag type="success">共享数据</ElTag>
                </div>

                <div class="text-right text-xs italic text-gray-400">
                  双击卡片进入管理页
                </div>
              </div>
            </ElCard>
          </template>
          <template v-else>
            <ElCard
              shadow="hover"
              class="mx-auto w-full max-w-md overflow-hidden rounded-2xl p-0 shadow-lg transition-all hover:scale-[1.01] dark:bg-gray-900"
              :body-style="{ padding: '0' }"
              @dblclick="$router.push('/quick-start/data')"
            >
              <!-- 背景图，可替换为 earth.jpg 或其他 -->
              <div class="h-48 w-full overflow-hidden">
                <img
                  :src="getMtdeUrl('earth')"
                  alt="公共 GIS 栅格服务"
                  class="h-full w-full object-cover"
                />
              </div>

              <!-- 卡片内容 -->
              <div class="p-6">
                <h3
                  class="mb-2 text-lg font-semibold text-gray-800 dark:text-gray-100"
                >
                  公共 GIS 栅格服务
                </h3>

                <p
                  class="mb-4 text-sm leading-relaxed text-gray-600 dark:text-gray-400"
                >
                  该服务提供共享的公共 GIS
                  栅格服务资源，可方便快捷的导入至个人服务，用于在可视化场景中进行地图配置。
                </p>

                <div class="mb-4 flex flex-wrap gap-2 text-xs">
                  <ElTag type="primary">栅格服务</ElTag>
                  <ElTag type="info">地图可视化</ElTag>
                  <ElTag type="success">共享数据</ElTag>
                </div>

                <div class="text-right text-xs italic text-gray-400">
                  双击卡片进入管理页
                </div>
              </div>
            </ElCard>
          </template>
        </div>

        <!-- 分页 -->
        <div
          v-if="filteredFiles.length > 0"
          class="col-span-2 mt-4 flex justify-center"
        >
          <ElPagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- HistoricalMap 组件 - 覆盖显示 -->
      <div
        v-if="showHistorical"
        class="absolute inset-0 z-10 h-full w-full overflow-hidden bg-white"
      >
        <!-- 返回按钮 -->
        <button
          @click="showHistorical = false"
          class="absolute right-3 top-3 z-50 rounded-full bg-gray-200 p-2 text-gray-500 hover:bg-gray-300 hover:text-gray-700"
          aria-label="返回"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="h-5 w-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
        <HistoricalMap :initial-year="1" />
      </div>
    </div>
  </Page>
</template>
